<?php
/**
 * k3玩法
 * Lion @ 20180115
 */
defined('IN_YuLin') || exit('NO PERMIT!');

//	彩票id
$lotteryid = NoBadStr($_GET['id']) ? intval(NoBadStr($_GET['id'])) : intval($_POST['cid']);
//	登录验证
UserLogin(U($m.'/'.$c.'/'.$a,['id'=>$lotteryid]));

// 获取彩种信息
foreach ($lottList as $k => $v){
    if ($v['id'] == $lotteryid){
        unset($v['content']);
        $lotteryInfo = $v;
        break;
    }
}
// 投注赔率查询
$rpsTab      = Table('repoint_and_odds');
$planMainTab = Table('lottery_play_main');
$planFollTab = Table('lottery_play_follow');
$where       = '';
foreach ($rpsInfo as $k => $v){
    if ($k == $lotteryInfo['cate_id']){
        $where = ' WHERE rps.lott_cate_id = "' . $k . '" AND rps.re_point = "' . $v['re_point'] . '"';
        break;
    }
}
$sql         = 'SELECT cate.`sname`, main.`en_code` as main_encode, main.`id` as main_id, main.`title` AS main_title, tp.`title` as type_title, tp.`en_code` as type_code,
                fo.`en_code` as foll_encode, fo.`title` AS foll_title, fo.`explain`, fo.`example`,
                rps.`re_point`, rps.`odds`
                FROM ' . $rpsTab . ' AS rps
                LEFT JOIN ' . $planFollTab . ' AS fo
                ON rps.`follow_id` = fo.`id`
                LEFT JOIN ' . $planMainTab . ' AS main
                ON main.`id` = fo.`main_id`
                LEFT JOIN yulin_lottery_category AS cate
                ON main.`cate_id` = cate.`id`
                LEFT JOIN yulin_lottery_play_type AS tp
                ON fo.`type_id` = tp.`id`
                ' . $where;
$playList    = $db->getall($sql);
$codeKeyList = array();
foreach ($playList as $k => $v){
    $v['explain'] = html_entity_decode($v['explain']);
    $codeKeyList[$v['main_encode']][$v['type_code']][$v['foll_encode']] = $v;
}

if($a == 'returnbl')
{
    if(IS_POST)
    {
        $id = trim($_POST['id']);
        $money = intval($_POST['money']);
        if($id == '和值')
        {
            $id = trim($_POST['code']);
        }
        $t = $db->getrow('SELECT bl FROM '.Table('lottery_type').' WHERE val = "'.$id.'" AND type = "k3"');
        echo number_format($t['bl'] * $money,2);
        exit;
    }
}

if($a == 'countnum3')
{
    if(IS_POST)
    {
        $str = trim($_POST['str'],',');
        $num = intval($_POST['num']);
        $arr = explode(',',$str);

        $n = getSequenceAry($arr,$num);
        $new = 0;
        foreach($n as $key=>$val)
        {
            if(count($val) == '3')
            {
                $new += 1;
            }
        }

        echo $new;
        exit;
    }
}
if($a == 'countnum2')
{
    if(IS_POST)
    {
        $str = trim($_POST['str'],',');
        $num = intval($_POST['num']);
        $arr = explode(',',$str);

        $n = getSequenceAry($arr,$num);
        $new = 0;
        foreach($n as $key=>$val)
        {
            if(count($val) == '2')
            {
                $new += 1;
            }
        }

        echo $new;
        exit;
    }
}
if($a == 'orderAdd')
{
    if(IS_POST)
    {
        $cid = intval($_POST['cid']);
        !$cid && AjaxReturn(1,'请选择彩票种类');

        $iid = $_POST['iid'] * 1;
        !$iid && AjaxReturn(1,'请选择彩票期号');

        //获取最新一期的彩票期号和用户投注的做对比
        $last = $db->getrow('SELECT k.id,k.period,t.title FROM '.Table('lottery_k3').' k 
        LEFT JOIN '.Table('lottery').' t ON k.tid = t.id where 
        k.tid = '.$cid.' and '.time().' >= k.starttime 
        and '.time().' < k.stoptime');
        
        $last['period'] != $iid && AjaxReturn(1,'当前期已经结束投注');

        $count = implode('#',$_POST['BettingCount']);

        $amount = intval($_POST['amount']);
        $amount <= 0 && AjaxReturn(1,'请选择投注项');

        $data = $_POST['BettingData'];
//        $orderno = date('YmdHis').str_pad($cid,2,0,STR_PAD_LEFT).str_pad($_uid,6,0,STR_PAD_LEFT).rand(1000,9999);
        $weimiao   = microtime(true);
        $orderno   = 'TZ' . date('YmdHis') . str_pad(substr($weimiao, strpos($weimiao, '.') + 1), '4', 0);

        $tmp = [];
        $tmp['uid']     =   $_uid;
        $tmp['tid']     =   'order_add';
        $tmp['lkey']    =   $orderno;
        $tmp['money']   =   $amount;
        $tmp['balance'] =   -$amount;
        $tmp['notes']   =   '下注购买彩票：'.$last['title'];
        $res = MoneyLog($tmp);
        !$res && AjaxReturn(1,'账户余额不足，请先充值');

        $ins = [];
        $ins['lott_id'] = $cid;
        $ins['uid'] = $_uid;
        $ins['order_no'] = $orderno;
        $ins['code'] = $count;
        $ins['period'] = $iid;
        $ins['amount'] = $amount;
        $ins['createtime'] = time();
        $oid = $db->add('lottery_order_main',$ins);
        !$oid && AjaxReturn(1,'下单失败,请刷新重试');

        include_once (ROOT_PATH.'module/lottery/lottery_play_betting.inc.php');
        // 代理返点相关，这里应该在下单后操作
        fanDian($ins, $oid);
        
        !is_array($data) && AjaxReturn(1,'请选择要投注的号码');
        $arr = k3odds();
        $arrEnPlay = GetEnPlayInfo();
        //先拼装一次
        $arrEnplay = array();
        if(!empty($data))
        {
            foreach($data as $k=> $v)
            {
                $strEnPlay = !empty(array_search( $v['betting_type'], $arrEnPlay)) ? array_search( $v['betting_type'], $arrEnPlay) : '';
                $data[$k]['en_play'] = $strEnPlay;
                if(!empty($strEnPlay))
                {
                    $arrEnplay[$strEnPlay][] = $v['betting_number'];
                }

            }
        }
        //拼装第二次
        $arrEnPlay1= array();
        foreach($arrEnplay as $k=> $v)
        {
            $arrEnPlay1[$k] = (!empty($v) && is_array($v)) ? implode(',', $v) : '';
        }
        
        // 整理赔率信息
        $k3KeyList   = $codeKeyList['TSK3-']['K3|'];
        $cklData     = array();
        foreach ($k3KeyList as $k => $v){
            if(strpos($k, 'HZ') !== false){
                $cklData[str_replace('和值', '', $v['foll_title'])] = $v;
            }
        }
        
        // 初始化投注赔率值，简化代码写法
        $playOdds = 0;
        foreach($data as $key=>$val)
        {
            $tmp = [];
            $tmp['o_id'] = $oid;
            $tmp['period_id'] = $last['id'];
            $tmp['lott_id'] = $cid;
            $tmp['en_play'] = $val['en_play'];
            $tmp['betting_str'] = isset($arrEnPlay1[$val['en_play']]) ? $arrEnPlay1[$val['en_play']] : '';
            $tmp['cn_play'] = $val['betting_type'];
            $tmp['betting_no'] = $val['betting_number'];
//            $tmp['num'] = $val['num'];
            $tmp['num'] = 1;
//            $tmp['money'] = $val['betting_money'].'***'.$val['betting_type'];//此字段为decimal
            $tmp['money'] = $val['betting_money'];
            $tmp['eo_money'] = $val['betting_money'];//新增
            if('HE' == $val['en_play'])
            {
                $tmp['odds'] = $arr[$val['en_play']][$val['betting_number']];
            }else{
                $tmp['odds'] = $arr[$val['en_play']];
            }
            if ($k3KeyList[$val['en_play']]){
                $playOdds = $k3KeyList[$val['en_play']]['odds'];
            }
            if ($val['en_play'] == 'HE'){
                // 和值是多赔率玩法
                $playOdds = $cklData[$tmp['betting_no']]['odds'];
            }
            $tmp['odds'] = $playOdds;
            $db->add('lottery_order_item',$tmp);
        }
        
        AjaxReturn(0,'下注成功！');
    }
}

!$lotteryid && ShowMsg('请选择彩种!',U('index/lotteryHall'));

$info = $db->getrow('select * from '.table('lottery').' where ptid = "K3" and id = '.$lotteryid);
!$info && ShowMsg('请重新选择彩种!',U('index/lotteryHall'));

//	所有K3玩法
$k3 = $db->getall('select * from '.table('lottery').' where ptid = "K3"');

//	当前投注的期号
//$k3info = $db->getrow('select * from '.table('lottery_k3').' where tid = '.$info['id'].' and starttime <= '.time().' and stoptime > '.time());
$k3info = $db->getrow('select * from '.table('lottery_k3').' where tid = '.$info['id'].' and stoptime > '.TIMESTAMP.' ORDER BY stoptime');
// if(!$k3info)
// {
//     ShowMsg('当前彩票没有期号,请重新选择!',U('index/lotteryHall'));
// }

$getLastSql = 'SELECT id, period, tid, `day`, `code` FROM ' . Table('lottery_k3') . ' WHERE tid = ' . $info['id'] . ' AND `code` != "" AND status = 1 ORDER BY id DESC limit 1';
$prek3info  = $db->getrow($getLastSql);
//	当前玩法投注记录
$playlist = $db->getall('select * from '.Table('lottery_k3_order').' where tid = ' . $lotteryid);

$list          = array();
$list['he']    = $db->getall('select val,bl from '.table('lottery_type').' where type = "k3" and types ="he"');
$list['sth']   = $db->getall('select val,bl from '.Table('lottery_type').' where type = "k3" and types ="sth"');
$list['slhtx'] = $db->getall('select val,bl from '.Table('lottery_type').' where type = "k3" and types ="slhtx"');
$nowTime       = date('m/d/Y H:i:s', time());
$codeKeyList   = json_encode($codeKeyList);
$tpl->display('index/k3');
